<template>
  <a-upload
    v-model:file-list="fileList"
    action="/api/image/avatar/upload"
    list-type="picture-card"
    :headers="headers"
    @preview="handlePosterPreview"
    @change="handleUploadChange"
    @remove="removeFile"
  >
    <div v-if="posters.length < 8">
      <plus-outlined />
      <div style="margin-top: 8px">上传</div>
    </div>
  </a-upload>
  <a-modal
    :visible="posterPreviewVisible"
    title="图片预览"
    :footer="null"
    @cancel="
      () => {
        posterPreviewVisible = !posterPreviewVisible;
      }
    "
  >
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script lang="ts" setup>
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineEmits,
  watch,
} from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import ResultEnum from "@/config/ResultEnum";
import { message } from "ant-design-vue";
import type { UploadProps } from "ant-design-vue";
import storage from "store";

interface PropsConfig {
  value: [];
  version: number;
}

const props = withDefaults(defineProps<PropsConfig>(), {
  value: [] as any,
  version: 0,
});

const emit = defineEmits(["update:value"]);

const posterPreviewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");
const posters = ref([] as any);

const headers = ref({
  token: storage.get("token"),
});

const fileList = ref([] as any);

const IMG_SERVER = import.meta.env.VITE_APP_IMG_SERVER;

const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

const handlePosterPreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }

  previewImage.value = file.url || file.preview;
  posterPreviewVisible.value = true;
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};

//海报上传事件
const handleUploadChange = (info: any) => {
  console.log(info.file);
  if (info.file.status !== "uploading") {
    //上传中
  }
  if (info.file.status === "done") {
    //上传完毕
    let res = info.file.response;
    if (res.code == ResultEnum.SUCCESS_CODE) {
      console.log("res is ", res);
      //上传成功
      message.success("上传成功");
      let imgs = posters.value;
      for (let item of res.result) {
        imgs.push({
          uid: item.uid,
          name: item.name,
          status: "done",
          url: IMG_SERVER + item.savePath,
          serverUrl: item.savePath,
        });
      }

      posters.value = imgs;
      fileList.value = imgs;
    } else {
      //上传失败
      message.error("图片上传失败");
    }
  } else if (info.file.status === "error") {
    //失败
  } else if (info.file.status == "removed") {
    //删除
  }
  console.log(fileList.value);
};

const setData = (data: any) => {
  posters.value = data;
  fileList.value = data;
};
const getData = () => {
  return fileList.value;
};

const removeFile = (file: any) => {};

watch(
  () => posters.value,
  (newVal: string) => {
    //emit("update:value", value);
    console.log(newVal);
  },
  {
    immediate: true,
  }
);

watch(
  () => props.value,
  (newVal: any) => {
    //emit("update:value", value);
    posters.value = newVal;
    fileList.value = newVal;
  },
  {
    immediate: true,
  }
);

watch(
  () => props.version,
  (newVal: number) => {
    fileList.value = [];
    posters.value = [];
  }
);

onMounted(() => {
  //posters.value = props.value;
});

defineExpose({
  setData,
  getData,
  posters,
  fileList,
  removeFile,
  headers,
});
</script>
